package com.beiding.jsonanalyzer.querylink;

import com.beiding.jsonanalyzer.flow.ValueNode;
import com.beiding.jsonanalyzer.flow.BranchNode;
import com.beiding.jsonanalyzer.flow.branchevents.StopNow;
import com.beiding.jsonanalyzer.flow.flowevents.DataNodeEvent;

public class RangeQueryLinkNode<W extends ValueNode> extends ComputeNode<W> {
    ;
    private int from;
    private int length = -1;

    public RangeQueryLinkNode(QueryLinkNode<W> preNode) {
        super(preNode);
    }

    public RangeQueryLinkNode<W> from(int from) {
        this.from = from;
        return this;
    }


    public RangeQueryLinkNode<W> length(int length) {
        this.length = length;
        return this;
    }

    @Override
    protected void bindByComputeNode(BranchNode<W> preResult, BranchNode<W> newBranchNode) {

        //如果为负值则查询所有
        if (length < 0) {
            length = Integer.MAX_VALUE;
        }

        //第一个数是跳过了多少,第二个数是去了多少
        int[] numbers = new int[]{0, 0};


        ComputeNodeUtils.bindControlEvent(preResult, newBranchNode);

        preResult.onDataEvent(DataNodeEvent.eventType(),event -> {
            if (numbers[0] < from) {
                numbers[0]++;
                return;
            }

            if (numbers[1] < length) {
                newBranchNode.signDataEvent(event);

                numbers[1]++;
            } else {

                //发送立刻停止的信号
                preResult.getBranch().emit(StopNow.success("范围查找结束"));

            }
        });


    }

}
